package cn.edu.ncut.cs.springboot.petmanagementsystem.service.Impl;

import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.FavoriteMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.ProductMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Favorite;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Product;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.FavoriteService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏夹Service实现类
 */
@Slf4j
@Service
public class FavoriteServiceImpl implements FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean addFavorite(Long userId, Long productId) {
        if (userId == null || productId == null) {
            throw new IllegalArgumentException("参数不完整");
        }

        // 检查商品是否存在
        Product product = productMapper.selectById(productId);
        if (product == null) {
            throw new IllegalArgumentException("商品不存在");
        }

        // 检查是否已收藏
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, userId);
        wrapper.eq(Favorite::getProductId, productId);
        Long count = favoriteMapper.selectCount(wrapper);
        if (count > 0) {
            throw new IllegalArgumentException("商品已在收藏夹中");
        }

        // 添加收藏
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setProductId(productId);
        favorite.setCreateTime(LocalDateTime.now());
        int result = favoriteMapper.insert(favorite);
        return result > 0;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean removeFavorite(Long favoriteId, Long userId) {
        if (favoriteId == null || userId == null) {
            return false;
        }

        // 验证收藏所有权
        Favorite favorite = favoriteMapper.selectById(favoriteId);
        if (favorite == null || !favorite.getUserId().equals(userId)) {
            throw new IllegalArgumentException("收藏不存在或无权操作");
        }

        int result = favoriteMapper.deleteById(favoriteId);
        return result > 0;
    }

    @Override
    public List<Product> getFavoriteList(Long userId) {
        if (userId == null) {
            return new ArrayList<>();
        }

        // 查询用户的收藏列表
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, userId);
        wrapper.orderByDesc(Favorite::getCreateTime);
        List<Favorite> favorites = favoriteMapper.selectList(wrapper);

        if (favorites.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取商品ID列表
        List<Long> productIds = favorites.stream()
                .map(Favorite::getProductId)
                .collect(Collectors.toList());

        // 查询商品信息
        List<Product> products = productMapper.selectBatchIds(productIds);

        // 按收藏时间排序（保持收藏顺序）
        return favorites.stream()
                .map(favorite -> products.stream()
                        .filter(product -> product.getId().equals(favorite.getProductId()))
                        .findFirst()
                        .orElse(null))
                .filter(product -> product != null)
                .collect(Collectors.toList());
    }

    @Override
    public boolean checkFavorite(Long userId, Long productId) {
        if (userId == null || productId == null) {
            return false;
        }

        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, userId);
        wrapper.eq(Favorite::getProductId, productId);
        Long count = favoriteMapper.selectCount(wrapper);
        return count > 0;
    }
}
